package com.bxd.baodan.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.fragment.AgeAndSexFragment;
import com.bxd.baodan.fragment.BaoxianFragment;
import com.bxd.baodan.fragment.BaseStepFragment;
import com.bxd.baodan.fragment.FamilyIncomeFragment;
import com.bxd.baodan.fragment.JobFragment;
import com.bxd.baodan.fragment.LifeTagFragment;
import com.bxd.baodan.fragment.MemberFragment;
import com.bxd.baodan.fragment.StudyFragment;
import com.bxd.baodan.item.FamDesignBean;
import com.bxd.baodan.item.PersonalDesignResultBean;
import com.bxd.baodan.logic.DesignStep;
import com.bxd.baodan.util.AppManager;
import com.bxd.baodan.util.LogUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.ShareUtil;
import com.bxd.baodan.util.StringUtil;
import com.bxd.baodan.util.ZoomOutPageTransformer;
import com.umeng.analytics.MobclickAgent;

/**
 * todo 需要传type
 */
public class PersonalDesignActivity extends BaseActivity {

    public SparseArray<BaseStepFragment> fragments;

    private FragmentStatePagerAdapter mAdapter;

    private TextView nextStep;

    public DesignStep designStep;
    private ViewPager viewPager;
    public FamDesignBean famDesignBean;

    String type;


    String reportId;
    boolean isMember;
    FragmentManager fm;
    private String role;
    ImageView share;
    BaseStepFragment[] mFragment = {
            new AgeAndSexFragment(), new JobFragment(), new LifeTagFragment(),
            new StudyFragment(), new FamilyIncomeFragment(), new BaoxianFragment(),
            new MemberFragment()
    };
    private Handler handler;
    public static final int SHARE_ERROR = 1;
    public static final int SHARE_CANCELED = 3;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_personal_design);
        setActionBarTitle("个人保险方案设计");


        findViewById(R.id.bar_iv_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                showExitDialog("确认退出方案设计吗?");

            }
        });

         share = findViewById(R.id.iv_bar_right);
         share.setImageResource(R.drawable.share);
         share.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 String url = "http://rest-02.bxd365.com/html/design/personal?step=1";
                 String imgUrl = "";
                 ShareUtil.showShareWindow(PersonalDesignActivity.this,
                         "智能保险方案设计",
                         "人工智能为您精准测算保险需求,快来试试吧!",
                         url,
                         imgUrl,
                         "",
                         handler);
             }
         });

        nextStep = (TextView) findViewById(R.id.next_step);

        viewPager = (ViewPager) findViewById(R.id.viewpager);

        if (!NetUtil.isNetworkConnect(this)) {
            viewPager.setVisibility(View.GONE);
            nextStep.setVisibility(View.GONE);
        } else {
            viewPager.setVisibility(View.VISIBLE);
            nextStep.setVisibility(View.VISIBLE);

        }

        designStep = new DesignStep(this);



        fm = getSupportFragmentManager();

        reportId = getIntent().getStringExtra("reportId");
        type = getIntent().getStringExtra("type");
        if (!StringUtil.isEmpty(reportId)) {
// TODO: 17/9/14 有reportId,是从js中调用的.
            isMember = true;
            role = getIntent().getStringExtra("role");


        } else {
            isMember = false;
            role = "my";
        }
        designStep.role = role;
        String roleText = "";
        if (role.equals("my")) {
            roleText = "您";

        } else if (role.equals("spouse")) {
            roleText = "您配偶";

        } else if (role.equals("father")) {
            roleText = "您父亲";

        } else if (role.equals("mother")) {
            roleText = "您母亲";
        } else if (role.equals("child")) {
            roleText = "您孩子";
        }

        designStep.roleText = roleText;


        final NetUtil netUtil = new NetUtil(this, JsonApi.DESIGN_CONDITION);
        netUtil.setParams("type", "0");
        netUtil.postRequest("加载中", new NetUtil.RequestStringListener() {
            @Override
            public void onComplete(String result) {
                famDesignBean = new Gson().fromJson(result, FamDesignBean.class);
            }
        });




        fragments = new SparseArray<>();
        int key = 0;
        fragments.put(key++, mFragment[0]);
        fragments.put(key++, mFragment[1]);


        nextStep.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                int curPosition = viewPager.getCurrentItem();

                if (designStep.nextStep(curPosition, isMember)) {

                    if (curPosition == 0) {
                        addItem();
                    }

                    if (designStep.isEnd) {
                        nextStep.setText("完成");


                        NetUtil netUtil1 = new NetUtil(PersonalDesignActivity.this, JsonApi.DESIGN_PERSONAL);
                        netUtil1.setParams("role", designStep.role);
                        netUtil1.setParams("type", type);
                        netUtil1.setParams("action", "doReport");
                        netUtil1.setParams("reportId", reportId);
                        netUtil1.setParams("gender", designStep.gender);
                        netUtil1.setParams("age", designStep.age);
                        netUtil1.setParams("career", designStep.career);
                        netUtil1.setParams("personalAnnualIncome", designStep.personal_annual_income);
                        netUtil1.setParams("lifeTag", designStep.life_tag);
                        netUtil1.setParams("haveSocialInsurance", designStep.have_social_insurance);
                        netUtil1.setParams("haveBusinessInsurance", designStep.have_business_insurance);
                        netUtil1.setParams("businessInsuranceLife", designStep.business_insurance_life);
                        netUtil1.setParams("businessInsuranceSerious", designStep.business_insurance_serious);
                        netUtil1.setParams("businessInsuranceAccident", designStep.business_insurance_accident);
                        netUtil1.setParams("businessInsuranceMedical", designStep.business_insurance_medical);
                        netUtil1.setParams("businessInsurancePension", designStep.business_insurance_pension);
                        netUtil1.setParams("businessInsuranceEducation", designStep.business_insurance_education);
                        netUtil1.setParams("educationPlan", designStep.education_plan);
                        netUtil1.setParams("familyMember", designStep.family_member);
                        LogUtil.e("family_member: " + designStep.family_member);
                        netUtil1.setParams("familyAnnualIncome", designStep.family_annual_income);
                        netUtil1.setParams("familyMonthSpending", designStep.family_month_spending);
                        netUtil1.setParams("familyMonthAlimony", designStep.family_month_alimony);
                        netUtil1.setParams("familyLoan", designStep.family_loan);

                        netUtil1.postRequest("生成结果", new NetUtil.RequestStringListener() {
                            @Override
                            public void onComplete(String result) {
                                PersonalDesignResultBean bean = new Gson().fromJson(result, PersonalDesignResultBean.class);
                                AppManager.getInstance().finishActivity(WebViewPager.class);

                                MobclickAgent.onEvent(App.getContext(), "v6_1_3_SY_ksxbx_ckbg");
                                openActivity(WebViewPager.class, new String[]{"startUrl"}, new String[]{bean.data.url});
                                finish();
                            }
                        });


                    }


                    try {
                        viewPager.setCurrentItem(curPosition + 1);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });


        mAdapter = new FragmentStatePagerAdapter(fm) {
            @Override
            public Fragment getItem(int position) {

                return fragments.valueAt(position);
            }

            @Override
            public int getCount() {

                return fragments.size();
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object object) {
                super.destroyItem(container, position, object);
            }

            @Override
            public int getItemPosition(Object object) {
                return POSITION_NONE;
            }

        };
        viewPager.setAdapter(mAdapter);
        viewPager.setOffscreenPageLimit(9);
        viewPager.setPageTransformer(true, new ZoomOutPageTransformer());

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {


            }

            @Override
            public void onPageScrollStateChanged(int state) {
                int currentItem = viewPager.getCurrentItem();
                int pre = currentItem - 1;


                if (!designStep.nextStep(pre, isMember) && currentItem > 0 && state == ViewPager.SCROLL_STATE_IDLE) {
                    viewPager.setCurrentItem(pre);
                }


                if (currentItem == 0 && state == ViewPager.SCROLL_STATE_DRAGGING && designStep.nextStep(currentItem, isMember)) {
                    addItem();
                }
            }
        });


    }

    private void addItem() {

        int age_ = Integer.parseInt(designStep.age);
        if (designStep.preAge < 0) {
            if (age_ < 18) {

                add0_18();
            } else if (age_ > 17 && age_ < 56) {
                add18_55();
            } else {
                add55_();
            }
        } else {
            if (age_ < 18) {
                if (designStep.preAge > 18) {
                    add0_18();
                }
            } else if (age_ > 17 && age_ < 56) {

                if (designStep.preAge < 18 || designStep.preAge > 55) {
                    add18_55();
                }


            } else {
                if (designStep.preAge < 55) {
                    add55_();
                }

            }


        }
        designStep.preAge = age_;

    }


    public void add0_18() {
        fragments.clear();
        int key = 0;
//        fragments.put(key++,new AgeAndSexFragment());
//        if (!isMember) {
//            fragments.put(key++, new FamilyIncomeFragment());
//        }
//        fragments.put(key++, new BaoxianFragment());  //3
//        fragments.put(key++, new StudyFragment());  //6

        fragments.put(key++, mFragment[0]);
        if (!isMember) {
            fragments.put(key++, mFragment[4]);
        }
        fragments.put(key++, mFragment[5]);  //3
        fragments.put(key++, mFragment[3]);  //6


        mAdapter.notifyDataSetChanged();

    }

    //
    public void add18_55() {


        fragments.clear();
        int key = 0;
//        fragments.put(key++,new AgeAndSexFragment());
//        fragments.put(key++, new JobFragment());
//        fragments.put(key++, new LifeTagFragment());
//        fragments.put(key++, new BaoxianFragment());
//        if (!isMember) {
//            fragments.put(key++, new MemberFragment());
//            fragments.put(key++, new FamilyIncomeFragment());
//        }


        fragments.put(key++, mFragment[0]);
        fragments.put(key++, mFragment[1]);  //3
        fragments.put(key++, mFragment[2]);
        fragments.put(key++, mFragment[5]);
        if (!isMember) {
            fragments.put(key++, mFragment[6]);
            fragments.put(key++, mFragment[4]);
        }

        mAdapter.notifyDataSetChanged();

    }

    public void add55_() {


        //  int key = 1;


        fragments.clear();
        int key = 0;
//        fragments.put(key++,new AgeAndSexFragment());
//        fragments.put(key++, new JobFragment());
//        fragments.put(key++, new LifeTagFragment());
//        fragments.put(key++, new BaoxianFragment());
//        if (!isMember) {
//            fragments.put(key++, new FamilyIncomeFragment());
//        }


        fragments.put(key++, mFragment[0]);
        fragments.put(key++, mFragment[1]);  //3
        fragments.put(key++, mFragment[2]);
        fragments.put(key++, mFragment[5]);
        if (!isMember) {
            fragments.put(key++, mFragment[4]);
        }


        mAdapter.notifyDataSetChanged();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            showExitDialog("确认退出方案设计吗?");
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
        }

    }
    /*
     * 监听分享的最终状态
     */
    private void createHandler() {
        if (handler == null) {

            handler = new Handler(new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {

                    switch (msg.what) {
                        case SHARE_ERROR:
                            Toast.makeText(PersonalDesignActivity.this, "分享失败",
                                    Toast.LENGTH_SHORT).show();
                            break;

                        case SHARE_CANCELED:
                            Toast.makeText(PersonalDesignActivity.this, "取消分享",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            break;
                    }
                    return false;
                }
            });
        }
    }

}
